package cn.zhxu.pack;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Utils {

    /**
     * 可写文件
     * @param filePath
     * @return
     */
    public static File writeableFile(String filePath) {
        File file = new File(filePath);
        File parent = file.getParentFile();
        if (!parent.exists() && !parent.mkdirs()) {
            System.err.println("不能创建目录：" + parent.getPath());
            System.exit(1);
        }
        return file;
    }

    /**
     * 判断是否是文本文件
     * @param file
     * @return
     */
    public static boolean isTxtFile(File file) {
        String name = file.getName();
        int index = name.lastIndexOf(".");
        if (index < 0 || index >= name.length() - 1) {
            return false;
        }
        String extName = name.substring(index + 1);
        for (String ext: Config.me().getBinarys()) {
            if (extName.equals(ext)) {
                return false;
            }
        }
        return true;
    }


    public static String fileToString(File file) {
        StringBuilder ret = new StringBuilder((int)file.length() + 3);
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line = br.readLine();
            if (line != null) {
                ret.append(line);
            } else {
                return ret.toString();
            }
            while ((line = br.readLine()) != null) {
                ret.append('\n').append(line);
            }
            return ret.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
